import md5 from 'js-md5'
export function signatureGenerate({ data }) {
  // 密钥
  let secret = Math.random().toString(36).substr(2)
  // 时间戳
  let timestamp = new Date().getTime()
  // console.table("signatureGenerate data:")
  // console.table(data)
  // post参数
  let dataStr = dataSerialize(dataSort(data))
  // console.info("signatureGenerate dataStr:"+dataStr)
  // 生成签名
  let str = dataStr + 'sc=' + secret + '&t=' + timestamp
  const sign = md5(str)
  return {
    signature: sign.toUpperCase(), // 将签名字母转为大写
    timestamp,
    secret
  }
}

// 参数排序
function dataSort(obj) {
  if (JSON.stringify(obj) == '{}' || obj == null) {
    return {}
  }
  let keyArr = []
  for (let key in obj) {
    keyArr.push(key)
  }
  keyArr.sort()
  keyArr.reverse()
  let newObj = {}
  for (let i = 0; i < keyArr.length; i++) {
    // if (obj[keyArr[i]]) {
      newObj[keyArr[i]] = obj[keyArr[i]]
    // }
  }
  return newObj
}

// 参数序列化
function dataSerialize(sortObj) {
  let strJoin = ''
  for (let key in sortObj) {
    strJoin += key + ':' + sortObj[key] + '+'
  }
  return strJoin
}
